package com.xzx.service;

import com.xzx.dto.CommonPage;
import com.xzx.dto.Tuple2;
import com.xzx.mapper.UserMapper;
import com.xzx.po.PermissionPO;
import com.xzx.po.RolePO;
import com.xzx.po.UserPO;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/8/18 14:08
 */
@Slf4j
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    public boolean doLogin(UserPO userPO, HttpServletRequest request) {
        UserPO newPO = userMapper.selectByUserNameAndPwd(userPO);
        if (userPO == null) {
            return false;
        }
        request.getSession().setAttribute("user", newPO);
        request.getSession().setAttribute("userName", newPO.getUserName());


        // 查询权限
        Set<String> permissions = permissionService.selectPermissionByUserId(newPO.getId()).stream().map(PermissionPO::getUrl).collect(Collectors.toSet());
        request.getSession().setAttribute("permissions", permissions);
        return true;
    }

    public CommonPage<UserPO> list(String query, int page, int size) {
        int count = userMapper.count(query);
        int totalPage = count % size == 0 ? count / size : count / size + 1;
        List<UserPO> list = userMapper.list(query, size, (page - 1) * size );
        CommonPage<UserPO> result = new CommonPage<>();
        result.setPage(page);
        result.setSize(size);
        result.setTotal(count);
        result.setTotalPage(totalPage);
        result.setData(list);
        result.setFirstPage(page == 1);
        result.setLastPage(page == totalPage);
        log.info("======result:{}", result);
        return result;
    }

    public void doAdd(UserPO userPO) {
        userMapper.insert(userPO);
    }

    public void delete(List<Integer> ids) {
        log.info("======ids:{}", ids);
        userMapper.delete(ids);
        roleService.deleteByUserId(ids);
    }

    public UserPO getById(Integer id) {
        return userMapper.getById(id);
    }

    public void doEdit(UserPO userPO) {
        userMapper.update(userPO);
    }

    /**
     * 返回已经分配和未分配的角色
     * @param id .
     * @return .
     */
    public Tuple2<List<RolePO>, List<RolePO>> selectAllRole(Long id) {
        List<RolePO> allRoles = roleService.selectAll();
        List<RolePO> assignRoles = roleService.selectByUserId(id);
        Set<Long> set = assignRoles.stream().map(RolePO::getId).collect(Collectors.toSet());
        List<RolePO> unassignRoles = allRoles.stream().filter(rolePO -> !set.contains(rolePO.getId())).toList();
        log.info("======assignRoles:{}, unassignRoles:{}", assignRoles, unassignRoles);
        return Tuple2.of(assignRoles, unassignRoles);
    }

    public void doAssign(Integer userId, List<Long> roleIds) {
        roleService.doAssign(userId, roleIds);
    }

    public void doUnassign(Integer userId, List<Long> roleIds) {
        roleService.doUnassign(userId, roleIds);
    }
}
